import redis from 'redis';
import { logger } from '#src/common/utils/logger.js';
import config from '#src/config/config.js';

class RedisService {
    constructor() {
        this.client = null;
        this.initialized = false;
        this.initializationPromise = null;
    }

    /**
     * 初始化Redis客户端
     */
    async initialize() {
        if (this.initialized) return;
        if (this.initializationPromise) return this.initializationPromise;

        this.initializationPromise = new Promise((resolve, reject) => {
            this.client = redis.createClient({
                url: config.redisConfig.url || `redis://${config.redisConfig.host || 'localhost'}:${Number(config.redisConfig.port) || 6379}`,
                password: config.redisConfig.password,
                username: config.redisConfig.username
            });

            this.client.on('error', (err) => {
                logger.error('Redis error:', err);
                if (!this.initialized) reject(err);
            });

            this.client.on('connect', () => {
                logger.info('Redis client connected');
            });

            this.client.connect()
                .then(() => {
                    this.initialized = true;
                    resolve();
                })
                .catch(err => {
                    this.initializationPromise = null;
                    reject(err);
                });
        });

        return this.initializationPromise;
    }

    /**
     * 设置键值对，带过期时间
     * @param {string} key - 键名
     * @param {string} value - 值
     * @param {number} expirySeconds - 过期时间(秒)
     */
    async setEx(key, seconds, value) {
          if (!this.initialized) {
            await this.initialize();
        }
        return this.client.setEx(key, seconds, value);
    }
    /**
     * 获取键对应的值
     * @param {string} key - 键名
     */
    async get(key) {
        if (!this.initialized) {
            await this.initialize();
        }
        return this.client.get(key);
    }

    /**
     * 删除键
     * @param {string} key - 键名
     */
    async del(key) {
        if (!this.initialized) {
            await this.initialize();
        }
        return this.client.del(key);
    }

    /**
     * 检查键是否存在
     * @param {string} key - 键名
     */
    async exists(key) {
        if (!this.initialized) {
            await this.initialize();
        }
        return this.client.exists(key);
    }
}

export const redisService = new RedisService();